import { useApi, useJumpPage, useLang, useHideTabbar } from "./open.js";
import { ref } from "vue";
import { onShow } from "@dcloudio/uni-app";
import { getTrack } from "../api/track.js";
import { getRouteParams } from "../tools/tools.js";
import { showToast } from "vant";
// import { useStore } from "vuex";
//---------分类页------------------

export const useCategoryState = () => {
  useHideTabbar();

  const [getCategoryList, store] = useApi("getCategoryList");
  const active = ref(1000);
  const list = ref([]);
  const page = ref(1);
  const activeSort = ref(0);
  const typeOptions = ref([]);
  const categoryIdList = ref([]);
  const options = ref({ name: [], ename: [] });
  const total = ref(100);

  const handleOptionsLan = () => (typeOptions.value = options.value[useLang(store) === "zh" ? "name" : "ename"]);

  const getList = async function () {
    const res = await getCategoryList(...arguments);
    if (res.code === 1) {
      list.value.push(...res.data.list);
      total.value = res.data.total;
      const idList = [];
      options.value.name.length = 0;
      options.value.ename.length = 0;
      res.data.catelist.forEach((i) => {
        ["name", "ename"].forEach((k) => options.value[k].push(i[k]));
        idList.push(i.id);
      });
      categoryIdList.value = idList;
    }
  };

  const loadMore = async () => {
    if (total.value && total.value <= list.value.length) {
      return showToast("已经到底了");
    }

    const param = { sort: activeSort.value, page: ++page.value };
    if (active.value) {
      Object.assign(param, { category_id: categoryIdList.value[active.value] });
    }
    await getList(param);
  };

  const refresh = async function () {
    page.value = 0;
    activeSort.value = 0;
    list.value.length = 0;
    await getList(...arguments);
  };

  const reSort = async function (val) {
    list.value.length = 0;
    await getList({
      sort: val,
      page: 1,
      category_id: categoryIdList.value[active.value],
    });
  };

  const onChange = (index) =>
    refresh({
      category_id: categoryIdList.value[index],
    });

  onShow(() => {
    if (list.value.length) {
      const price_1 = list.value[0].price;
      isNaN(Number(price_1)) && store.getters["user/isLogin"] && refresh();
      handleOptionsLan();
      return;
    }

    getList();
    handleOptionsLan();
  });

  return { list, total, typeOptions, getList, onChange, reSort, active, activeSort, loadMore };
};

export const usePickerSelect = (options, conformFn) => {
  const columns = ref(options);
  const showPicker = ref(false);
  const active = ref({
    text: options[0].text,
    value: options[0].value,
  });

  const onConfirm = ({ selectedOptions }) => {
    Object.assign(active.value, selectedOptions[0]);
    conformFn && conformFn(selectedOptions[0]);
    showPicker.value = false;
  };

  const onCancel = () => (showPicker.value = false);

  return { columns, showPicker, active, onConfirm, onCancel };
};

export const useTrackInfo = () => {
  const statusMapper = {
    inforeceived: "快递员已收到包裹信息，正要取件。",
    transit: "包裹在运输途中。",
    pickup: "包裹已到达当地地点或正在前往您家的途中。",
    undelivered: "已尝试递送包裹，但由于某些原因而失败。通常，快递员会很快安排另一次送货。",
    delivered: "包裹已签收！",
    notfound: "包裹信息目前查询不到。",
    exception: "包裹可能已退回给发件人、损坏、丢失或其他异常。",
    expired: "包裹最后一条轨迹距今30天未更新。发生这种情况时，请联系快递员查询更多详细信息。",
    pending: "新增包裹正在查询中，请等待。",

    inforeceived001: "包裹正在等待快递员取件。",
    transit001: "包裹正在前往目的地的途中。",
    transit002: "包裹到达中心或分拣中心。",
    transit003: "包裹到达送货地。",
    transit004: "包裹到达目的地国家。",
    transit005: "清关完成。",
    transit006: "物品已发货。",
    transit007: "从机场出发。",
    pickup001: "包裹正在派送中或即将派送。",
    pickup002: "包裹到达代收点等待自取。",
    pickup003: "派送中，物流商已经与收件人联系过至少一次。",
    delivered001: "包裹投递成功。",
    delivered002: "客户自提成功。",
    delivered003: "包裹由客户签字签收。",
    delivered004: "包裹放至快递柜，或由物业、门卫代收。",
    undelivered001: "包裹由于地址问题投递失败。",
    undelivered002: "派送时无人在家。",
    undelivered003: "无法联系到收件人。",
    undelivered004: "由于其他原因导致派送失败。",
    exception004: "包裹无人认领。",
    exception005: "其他异常情况。",
    exception006: "包裹被海关扣留。",
    exception007: "包裹破损、遗失或被丢弃。",
    exception008: "订单在揽件前被取消。",
    exception009: "收件人拒收包裹。",
    exception010: "包裹已退回发件人处。",
    exception011: "包裹正在被退回发件人的途中。",
    notfound002: "包裹正在等待被揽件。",
    expired001: "包裹最后一条轨迹距今30天未更新。发生这种情况时，请联系快递员查询更多详细信息。",
  };

  const detail = ref({});
  const trackNum = ref(getRouteParams("id"));
  const trackName = ref(getRouteParams("name"));

  const getTrackInfo = async function () {
    const res = await getTrack(trackNum.value);
    detail.value = res.data?.success[0];

    console.log(detail.value);
  };

  onShow(() => getTrackInfo());

  return { trackNum, trackName, detail, getTrackInfo, statusMapper };
};

export const useChatManager = () => {
  const list = ref([]);
  const inputValue = ref("");
  const userid = ref(0);
  const [getChatList, sendChat, uploadChat, cancelChat, store] = useApi([
    "getChatList",
    "sendChat",
    "uploadChat",
    "cancelChat",
  ]);

  const sendMessage = (key) => {
    console.log(key);
    // sendChat({ senderId: userid.value, content: inputValue.value })
  };

  onShow(async () => {
    userid.value = store.getters["user/getUserId"] || 0;
    const res = await getChatList({ mid: userid.value, page: 1, sizer: 10 });
  });

  return { list, inputValue, sendMessage };
};

export const useMsgManager = () => {
  const list = ref({});
  const [getChannel] = useApi(["getChannel"]);

  const getAllChannelMsg = async () => {
    const res = await getChannel();
    list.value = res.data;
  };

  onShow(() => {
    getAllChannelMsg();
  });

  return { list };
};

export const useMsgList = () => {
  const list = ref([]);
  const [getMsgList] = useApi(["getMsgList"]);

  const getMsgListByTypeId = async () => {
    const res = await getMsgList({ typeId: getRouteParams("typeid") });
    list.value = res.data.list;
  };

  onShow(() => {
    getMsgListByTypeId();
  });

  return { list };
};

export const useInvoiceData = () => {
  const [getInvoice] = useApi(["getInvoice"]);

  const invoiceData = ref({});

  onShow(async () => {
    const res = await getInvoice({ orderno: getRouteParams("orderno") });
    invoiceData.value = res.data;
  });

  return [invoiceData];
};
